import type { IAuthLoginRes, IDoubleTokenRes } from './types/login'
import { http } from '@/http/http'
import request from '@/http/request'

/**
 * 登录表单
 */
export interface ILoginForm {
  tenantId: string
  username: string
  password: string
  code: string
  uuid: string
  clientId?: string
  grantType?: string
}

/**
 * 获取验证码
 * @returns ICaptcha 验证码
 */
export function getCodeImg() {
  return request({
    url: '/auth/code',
    headers: {
      isToken: false,
    },
    method: 'GET',
    timeout: 20000,
  })
}

/**
 * 用户登录
 * @param loginForm 登录表单
 */
export function login(loginForm: ILoginForm) {
  const params = {
    ...loginForm,
    clientId: loginForm.clientId || import.meta.env.VITE_APP_CLIENT_ID,
    grantType: loginForm.grantType || 'password',
  }
  return request({
    url: '/auth/login',
    headers: {
      isToken: false,
      isEncrypt: true,
    },
    method: 'POST',
    data: params,
  })
}

// 注册方法
export function register(data) {
  return request({
    url: '/register',
    headers: {
      isToken: false,
    },
    method: 'POST',
    data,
  })
}

// 获取租户列表
export function getTenantList() {
  return request({
    url: '/auth/tenant/list',
    headers: {
      isToken: false,
    },
    method: 'GET',
  })
}

/**
 * 刷新token
 * @param refreshToken 刷新token
 */
export function refreshToken(refreshToken: string) {
  return http.post<IDoubleTokenRes>('/auth/refreshToken', { refreshToken })
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
  return request({
    url: '/system/user/getInfo',
    method: 'GET',
  })
}

/**
 * 退出登录
 */
export function logout() {
  return request({
    url: '/auth/logout',
    method: 'POST',
  })
}

/**
 * 获取微信登录凭证
 * @returns Promise 包含微信登录凭证(code)
 */
export function getWxCode() {
  return new Promise<UniApp.LoginRes>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: res => resolve(res),
      fail: err => reject(new Error(err)),
    })
  })
}

/**
 * 微信登录
 * @param params 微信登录参数，包含code
 * @returns Promise 包含登录结果
 */
export function wxLogin(data: { code: string }) {
  return http.post<IAuthLoginRes>('/auth/wxLogin', data)
}
